package com.cskaoyan.service;

import com.cskaoyan.bean.MarketAddress;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketAddressMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Austin Hsu
 * @Date 2022/9/12 15:29
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    MarketAddressMapper marketAddressMapper;


    @Override
    public CommonData<MarketAddress> query() {
        PageHelper.startPage(1, 8);     //一页八条

        //得到User信息
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer uid = marketUser.getId();

        List<MarketAddress> list = marketAddressMapper.selectByUserId(uid);
        PageInfo<MarketAddress> pageInfo = new PageInfo<>(list);    //这个其实就是PageHelper提供的一个接收分页数据的类
        int total = (int) pageInfo.getTotal();
        int pages = pageInfo.getPages();

        CommonData<MarketAddress> data = new CommonData<>(total, pages, 8, 1, list);

        return data;
    }

    @Override
    public MarketAddress getDetail(Integer id) {
        MarketAddress data = marketAddressMapper.queryDetailedAddress(id);
        return data;
    }


    /**
     * 如果是新增 id=0
     * 如果是修改 id=那个被修改的id
     * 所以id=0时要先置空 再返回自增主键
     * @param marketAddress
     * @return
     */
    @Override
    public Integer postDetail(MarketAddress marketAddress) {
        if (marketAddress.getIsDefault()==true){          //要修改为默认地址
            marketAddressMapper.updateAllAddressNoDefault();
        }
        marketAddress.setUpdateTime(new Date());    //修改时间


        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer uid = marketUser.getId();            //得到User信息

        if (marketAddress.getId() != 0) {
            marketAddressMapper.updateByAddressId(marketAddress);   //执行修改 修改地址
        }else{
            marketAddress.setUserId(uid);
            marketAddress.setId(null);
            marketAddressMapper.insertAddress(marketAddress);      //执行insert 新增地址
        }
        return marketAddress.getId();

    }

    @Override
    public void deleteDetail(Map<String, Integer> map) {
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            int i=entry.getValue();
            marketAddressMapper.deleteByAddressId(i);
        }

    }
}
